package com.gr.blog.login.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gr.blog.dept.model.DeptModel;
import com.gr.blog.dept.service.DeptService;
import com.gr.blog.login.service.LoginService;
import com.gr.blog.user.model.UserModel;
import com.gr.blog.utils.CollectionsUtil;

@Controller
public class LoginAction {
	private static final Logger logger = Logger.getLogger(LoginAction.class);
	
	@Autowired
	@Qualifier("loginService")
	private LoginService loginService;
	
	@Autowired
	@Qualifier("deptService")
	private DeptService deptService;
	
	@RequestMapping("login")
	public String login(UserModel user,HttpServletRequest request,HttpServletResponse response) throws IOException{
		logger.error("[用户登陆时传入的信息]:"+user);
		HttpSession session = request.getSession();
		List<UserModel> userIsExit = userLoginAssist(user);
		if (CollectionsUtil.isListNotEmpty(userIsExit)) {
			logger.error("[用户登陆时的信息]："+userIsExit.get(0));
			session.setAttribute("userModel", userIsExit.get(0));
			session.setMaxInactiveInterval(30*60);
			return "index/index";
		} 
		return "login/login";
	}
	
	/**
	 * 用户登陆的辅助方法
	 * 2018年6月13日 下午5:20:15
	 * @return
	 * List<DeptModel>
	 */
	public List<UserModel> userLoginAssist(UserModel user){
		List<UserModel> userIsExit = loginService.findUserByUP(user);
		if (CollectionsUtil.isListNotEmpty(userIsExit)) {
			UserModel um = userIsExit.get(0);
			String uid = um.getUid();
			//根据uid查询对应部门的信息
			List<DeptModel> deptList = deptService.getDeptInfoByUserName(uid);
			um.setDeptList(deptList);
			return userIsExit;
		}
		return null;
	}
	
	@RequestMapping("ajaxVildUser")
	public @ResponseBody void ajaxVildUser(UserModel user,HttpServletRequest request,HttpServletResponse response) throws IOException{
		logger.error("[ajaxVildUser#校验用户信息时传人的参数]:"+user);
		int isExtis = loginService.ajaxVildUser(user);
		logger.error("[ajaxVildUser#校验用户时查询得到的结果]:"+isExtis);
		response.setContentType("text/html;charset=utf-8");
		if (isExtis <= 0) {
			response.getWriter().print("{\"success\": true,\"flag\":\"false\", \"msg\":\"用户名或者密码错误，请重试！！！\"}");
		} else  {
			List<UserModel> userIsExit = userLoginAssist(user);
			List<DeptModel> deptList = userIsExit.get(0).getDeptList();
			if (CollectionsUtil.isListNotEmpty(deptList)) {
				response.getWriter().print("{\"success\": true,\"flag\":\"true\", \"msg\":\"您老暂时没有权限,请找管理员赋权之后再登陆\"}");
			} else {
				response.getWriter().print("{\"success\": true,\"flag\":\"true\", \"msg\":\"\"}");
			}
		}
	}
}
